package com.wsc.springbootmultidevdemo.msg.pubnsub;

import com.rabbitmq.client.*;
import com.wsc.springbootmultidevdemo.msg.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 订阅者 1
 */
public class Worker1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        //同一时间只能接收一条消息
        channel.basicQos(1);

        String qName = "queue1";
        String exName = "fanout";

        channel.queueDeclare(qName,false,false,false,null);
        //声明交换机 FANOUT:广播 rabbitmq 中 exchange 没有存储能力 只有 queue 有存储能力
        channel.exchangeDeclare(exName, BuiltinExchangeType.FANOUT);
        //绑定队列
        channel.queueBind(qName,exName,"");
        System.out.println("Consumer is waiting for message");

        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body,"UTF-8");
                System.out.println("receive a message :"+message);
            }
        };
        channel.basicConsume(qName,true,consumer);
    }
}
